import FactorAPI from '@/api/Factor';
import FormulaAPI from '@/api/Formula';
import ProductCommon from '@/api/ProductCommon';
import {
  Box,
  ClickModal,
  createSharedHook,
  FormSection,
  useCall,
  useDictionary,
  usePubSub,
  usePubSubState,
  useReq,
  useSimpleMemo,
} from '@/components';
import { forkHandler } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, Form, Input, Table, Tabs } from 'antd';
import React, { useEffect, useMemo } from 'react';

function PromptPoolTable() {
  const columns = useMemo(
    () => [
      { dataIndex: 'value', title: '信息代码', width: 120 },
      { dataIndex: 'label', title: '返回信息' },
    ],
    [],
  );
  const pubsub = usePubSub();
  const value = usePubSubState(pubsub);
  const selected = useSimpleMemo(value == null ? [] : [value]);
  const dict = useDictionary('prompt_pool');
  const onSelect = useCall((keys) => {
    pubsub.update(keys[0] ?? null);
  });
  const rowSelection = useSimpleMemo({
    type: 'radio',
    onChange: onSelect,
    selectedRowKeys: selected,
  });

  return (
    <>
      {/*<FieldEffect name='msgCode' pubsub={pubsub} />*/}
      <Table
        size='middle'
        pagination={false}
        scroll={useSimpleMemo({ y: 'max(240px, min(720px, calc(100vh - 640px)))' })}
        columns={columns}
        rowKey='value'
        dataSource={dict}
        // rowSelection={rowSelection}
      />
    </>
  );
}

const useSharedFactorPool = createSharedHook(() => {
  const xhr = useReq(FactorAPI.findByPage);
  xhr.startOnce({});
  const refresh = useCall(() => xhr.start({}));
  return useSimpleMemo([xhr.result?.data?.records ?? [], xhr.status === 'loading', refresh]);
}, [[], false]);

function FactorTable() {
  const columns = useMemo(
    () => [
      { dataIndex: 'cname', title: '因子名称' },
      { dataIndex: 'code', title: '因子代码' },
    ],
    [],
  );
  const [data, loading] = useSharedFactorPool();

  return (
    <Table
      size='middle'
      pagination={false}
      scroll={useSimpleMemo({ y: 'max(240px, min(720px, calc(100vh - 640px)))' })}
      loading={loading}
      columns={columns}
      rowKey='code'
      dataSource={data}
    />
  );
}

const useSharedFormulaPool = createSharedHook(() => {
  const xhr = useReq(FormulaAPI.findByPage);
  xhr.startOnce({});
  const refresh = useCall(() => xhr.start({}));
  return useSimpleMemo([xhr.result?.data?.records ?? [], xhr.status === 'loading', refresh]);
}, [[], false]);

function FormulaTable() {
  const columns = useMemo(
    () => [
      { title: '代码', dataIndex: 'code', width: 80 },
      { title: '名称', dataIndex: 'formulaName' },
    ],
    [],
  );
  const [data, loading] = useSharedFormulaPool();

  return (
    <Table
      size='middle'
      pagination={false}
      scroll={useSimpleMemo({ y: 'max(240px, min(720px, calc(100vh - 640px)))' })}
      loading={loading}
      columns={columns}
      rowKey='code'
      dataSource={data}
    />
  );
}

function RuleConfigModal({ item, onOk, onToggle, ...rest }) {
  const [form] = Form.useForm();

  const validator = useCall((rule, value) =>
    ProductCommon.validateFormula(value, 'm', { hideMsg: 1 }).catch((error) => Promise.reject(error.msg)),
  );
  const rules = useSimpleMemo([
    { required: true, message: '请输入公式' },
    { validator, message: '公式校验失败' },
  ]);
  const validate = useCall(() => form.validateFields());

  useEffect(() => {
    if (item) form.setFieldsValue(item);
  }, [item]);

  const handleOk = useCall(async () => {
    const values = await form.validateFields().catch(catchAndScrollFor(form));
    /*if (values.msgCode == null) {
     message.warn('请选择返回信息');
     return false;
     }*/
    onOk?.({ ...item, ...values });
  });

  const handleToggle = useCall(
    forkHandler(onToggle, (visi) => {
      if (visi) item ? form.setFieldsValue(item) : form.resetFields();
    }),
  );

  const content = (
    <>
      <Form form={form} component={false}>
        <FormSection title='公式表达式'>
          <Form.Item name='ruleSentence' rules={rules} hasFeedback>
            <Input.TextArea />
          </Form.Item>
          <Box py={1}>
            <Button type='primary' onClick={validate}>
              验证公式
            </Button>
          </Box>
        </FormSection>

        <Tabs defaultActiveKey='msg'>
          <Tabs.TabPane tab='信息' key='msg'>
            <PromptPoolTable />
          </Tabs.TabPane>

          <Tabs.TabPane tab='变量' key='factor'>
            <FactorTable />
          </Tabs.TabPane>

          {/*<Tabs.TabPane tab='公式列表' key='formula'>
           <FormulaTable />
           </Tabs.TabPane>*/}
        </Tabs>
      </Form>
    </>
  );

  return <ClickModal title='公式' {...rest} content={content} onOk={handleOk} onToggle={handleToggle} />;
}

export default RuleConfigModal;
